package com.example.cosplay.controller;

import com.example.cosplay.model.DownloadProgress;
import com.example.cosplay.model.DownloadResult;
import com.example.cosplay.service.WallpaperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api/wallpaper")
@Slf4j
public class WallpaperController {

    private final WallpaperService wallpaperService;
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public WallpaperController(WallpaperService wallpaperService) {
        this.wallpaperService = wallpaperService;
    }

    @GetMapping("/download")
    public ResponseEntity<DownloadResult> downloadWallpaper() {
        String result = wallpaperService.fetchAndDownloadWallpaper();
        return ResponseEntity.ok(new DownloadResult(result, null));
    }
    
    @GetMapping("/download/{count}")
    public ResponseEntity<List<DownloadResult>> downloadMultipleWallpapers(
            @PathVariable int count,
            @RequestParam(required = false, defaultValue = "E:\\autoImg") String downloadPath) {
        
        List<DownloadResult> results = new ArrayList<>();
        
        for (int i = 1; i <= count; i++) {
            log.info("下载壁纸 {}/{}", i, count);
            String result = wallpaperService.fetchAndDownloadWallpaper(downloadPath);
            log.info("下载进度: {}/{} - {}", i, count, result);
            
            // 提取图片路径并创建结果对象
            String imagePath = extractImagePath(result);
            DownloadResult downloadResult = new DownloadResult(
                    formatResultMessage(result, i, count),
                    imagePath
            );
            results.add(downloadResult);
        }
        
        return ResponseEntity.ok(results);
    }
    
    @GetMapping("/progress/{sessionId}")
    public SseEmitter trackProgress(@PathVariable String sessionId) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        emitters.put(sessionId, emitter);
        
        emitter.onCompletion(() -> emitters.remove(sessionId));
        emitter.onTimeout(() -> emitters.remove(sessionId));
        
        // 发送初始进度
        try {
            emitter.send(SseEmitter.event()
                    .name("PROGRESS")
                    .data(new DownloadProgress(0, "准备下载...")));
        } catch (IOException e) {
            emitter.completeWithError(e);
        }
        
        return emitter;
    }
    
    @PostMapping("/download-async/{count}")
    public ResponseEntity<String> downloadAsync(
            @PathVariable int count,
            @RequestParam String sessionId,
            @RequestParam(required = false, defaultValue = "E:\\autoImg") String downloadPath) {
        
        executorService.submit(() -> {
            List<DownloadResult> results = new ArrayList<>();
            
            try {
                for (int i = 1; i <= count; i++) {
                    updateProgress(sessionId, (i - 1) * 100 / count, "正在下载第 " + i + " 张壁纸，共 " + count + " 张");
                    
                    String result = wallpaperService.fetchAndDownloadWallpaper(downloadPath);
                    log.info("下载进度: {}/{} - {}", i, count, result);
                    
                    // 提取图片路径并创建结果对象
                    String imagePath = extractImagePath(result);
                    DownloadResult downloadResult = new DownloadResult(
                            formatResultMessage(result, i, count),
                            imagePath
                    );
                    results.add(downloadResult);
                    
                    updateProgress(sessionId, i * 100 / count, "已完成 " + i + " 张壁纸下载，共 " + count + " 张");
                }
                
                // 发送完成事件
                SseEmitter emitter = emitters.get(sessionId);
                if (emitter != null) {
                    emitter.send(SseEmitter.event()
                            .name("COMPLETE")
                            .data(results));
                    emitter.complete();
                }
                
            } catch (Exception e) {
                log.error("下载过程中出错", e);
                SseEmitter emitter = emitters.get(sessionId);
                if (emitter != null) {
                    try {
                        emitter.send(SseEmitter.event()
                                .name("ERROR")
                                .data("下载失败: " + e.getMessage()));
                        emitter.complete();
                    } catch (IOException ex) {
                        emitter.completeWithError(ex);
                    }
                }
            }
        });
        
        return ResponseEntity.ok(sessionId);
    }
    
    private void updateProgress(String sessionId, int percentage, String message) {
        SseEmitter emitter = emitters.get(sessionId);
        if (emitter != null) {
            try {
                DownloadProgress progress = new DownloadProgress(percentage, message);
                emitter.send(SseEmitter.event()
                        .name("PROGRESS")
                        .data(progress));
            } catch (IOException e) {
                emitters.remove(sessionId);
                emitter.completeWithError(e);
            }
        }
    }
    
    private String extractImagePath(String result) {
        if (result != null && result.contains("Image successfully downloaded to:")) {
            return result.substring(result.indexOf(":") + 1).trim();
        }
        return null;
    }
    
    private String formatResultMessage(String result, int current, int total) {
        if (result != null && result.contains("Image successfully downloaded to:")) {
            String path = result.substring(result.indexOf(":") + 1).trim();
            return "第 " + current + "/" + total + " 张壁纸下载成功，保存至: " + path;
        } else if (result != null) {
            return "第 " + current + "/" + total + " 张壁纸下载失败: " + result;
        }
        return "下载失败，未知错误";
    }
} 